/**
 * 
 * 
 * 
 * Author: Matthias Van Eeghem <matthias@van-eeghem.com>
 * All rights reserved.
 * 
 */

package com.bomberman.gui;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;

import com.bomberman.Main;
import com.bomberman.player.PlayerManager;





import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

@SuppressWarnings("serial")
public class JoinGame extends JPanel implements ActionListener
{
	/**
	 * Holds the main object (menu etc)
	 */
	private Main main = null;
	/**
	 * Hold the connect button
	 */
    JButton connectButton;
    /**
     * Hold the back button
     */
    JButton backButton;
    /**
     * Hold the list of all IPs
     */
	List<String> ipList;
	/**
	 * Hold the server table
	 */
	JTable serverTable;
	
	/**
	 * Constructor of the object
	 */
	public JoinGame(Main main)
	{
		super(new GridLayout());
		
		// Initialise the buttons
		connectButton = new JButton("Connect");
		backButton = new JButton("Back");
		
		this.main = main;
		this.ipList = new ArrayList<String>();
	    this.setBackground(new Color(102, 171, 250));
	    
	    // Request all servers from the masterlist
	    loadServerList();
	}
	
	/**
	 * This method request all servers from the master list
	 */
	public void loadServerList()
	{
		// Initialise the list
		List<String> serverList = new ArrayList<String>();

		try 
		{
			// Request the master list
			BufferedReader reader = new BufferedReader(new InputStreamReader(new URL("http://matthias.van-eeghem.com/dev/JavaBomb/InternetList.php").openStream()));

			// Read one line per time
			String line;
		    while ((line = reader.readLine()) != null) 
		    {
		    	serverList.add(line);
		    }
		}
		catch (Exception error) 
		{
			// Error
		}
		
		// Initialise the row and column data
		String[][] rowData = new String[serverList.size() + 1][5];
	    String columnNames[] = { "Hostname", "Version", "IP", "Online players", "Max players" };
		
		int iAmountOfServers = 0;
		
		// Loop through all servers
		for(String server : serverList)
		{
	    	String[] serverData = server.split("-");
	    	
	    	rowData[iAmountOfServers][0] = serverData[2];
	    	rowData[iAmountOfServers][1] = serverData[1];
	    	rowData[iAmountOfServers][2] = serverData[0];
	    	rowData[iAmountOfServers][3] = serverData[3];
	    	rowData[iAmountOfServers++][4] = "" + PlayerManager.MAX_PLAYERS;
	    	
	    	ipList.add(serverData[0]);
		}
		
		// Add the localhost for debug purposes
		rowData[iAmountOfServers][0] = "Localhost";
		rowData[iAmountOfServers][1] = "Some version";
		rowData[iAmountOfServers][2] = "127.0.0.1:6161";
		rowData[iAmountOfServers][3] = "1";
		rowData[iAmountOfServers][4] = "4";
		ipList.add("127.0.0.1:6161");
		
		// Initialise the server table
	    serverTable = new JTable(rowData, columnNames) {
	        private static final long serialVersionUID = 1L;

	        public boolean isCellEditable(int row, int column) {                
	                return false;
	        };
	    };
	    
	    // You can only select one row a time
	    serverTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	    
	    // Add the mouse listener
	    serverTable.addMouseListener(new MouseAdapter() 
	    {
	    	public void mouseClicked(MouseEvent e) 
	    	{
	    		if (e.getClickCount() == 2) 
	    	    {
	    	    	int row = serverTable.getSelectedRow();
	    	    	
	    	    	if(row != -1)
						try {
							connectTo(ipList.get(row));
						} catch (NumberFormatException | ClassNotFoundException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
	    	    }
	    	}
	    });
	    
	    // Add listeners to the buttons
	    connectButton.addActionListener(this);
	    backButton.addActionListener(this);

	    // Make a scroll and split pane
	    JScrollPane scrollPane = new JScrollPane(serverTable);
	    JPanel buttonPane = new JPanel();
	    // Add the buttons
	    buttonPane.add(connectButton);
	    buttonPane.add(backButton);
	    
	    JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, buttonPane, scrollPane);
	    splitPane.setEnabled(false);
	    splitPane.setDividerLocation(40);
	    
	    add(splitPane);
	}
	
	/**
	 * Called when a button is clicked
	 */
	public void actionPerformed(ActionEvent e) 
	{
		// Host game button
		if(e.getSource() == connectButton)
		{
	    	int row = serverTable.getSelectedRow();

	    	if(row != -1)
				try {
					connectTo(ipList.get(row));
				} catch (NumberFormatException | ClassNotFoundException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
		}
		
		else if(e.getSource() == backButton)
		{
			main.setVisible(true);
			main.joinGameFrame.setVisible(false);
		}
	}
	
	/**
	 * This method connects the client to a game
	 * 
	 * @param IP
	 * @throws NumberFormatException
	 * @throws ClassNotFoundException
	 */
	public void connectTo(String IP) throws NumberFormatException, ClassNotFoundException
	{
		// Split the string and ip and port
		String[] IpAndPort = IP.split(":");
		
		// Hide this frame
		main.joinGameFrame.setVisible(false);
		
		try 
		{
			main.joinGame(IpAndPort[0], Integer.parseInt(IpAndPort[1]));
		} 
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
           